package com.csesteel.crm.control;

import com.csesteel.crm.domain.CrmRole;
import com.csesteel.crm.domain.User;
import com.csesteel.crm.service.CrmRoleService;
import com.csesteel.crm.service.UserService;
import com.csesteel.crm.util.MD5Util;
import com.csesteel.crm.util.WebUtil;
import com.csesteel.crm.vo.ResponseInfo;
import com.csesteel.crm.vo.UserSessionInfor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.Response;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/crm")
public class UserController extends BaseController{
    private Log logger = LogFactory.getLog(UserController.class);
    @Autowired
    private UserService userService;

    @Autowired
    private CrmRoleService crmRoleService;


    @RequestMapping("/androidTest")
    public void androidTest(HttpServletRequest request) throws UnsupportedEncodingException {
//        request.setCharacterEncoding("UTF-8");
        String eiinfo = request.getParameter("eiinfo");
        System.out.print("eiinfo:"+eiinfo);
    }

    @RequestMapping("/index")
    public String index(){
        return "index";
    }
    @RequestMapping("/error")
    public String error(){
        return "error";
    }

    @RequestMapping("/deleteUserById")
    public void printHello(HttpServletRequest request,HttpServletResponse response) {
        RequestContext requestContext = new RequestContext(request);
        String userId = request.getParameter("userId");
        ResponseInfo responseInfo = new ResponseInfo();
        responseInfo.setResult("0");
        responseInfo.setMessage(requestContext.getMessage("user.delete.success"));
        userService.deleteUser(userId);
        WebUtil.responseToJson(response, responseInfo);
    }

    @RequestMapping("/saveAuthUserByRole")
    public void saveAuthUserByRole(HttpServletRequest request,HttpServletResponse response) {
        RequestContext requestContext = new RequestContext(request);
        String suserId = request.getParameter("userId");
        String sroleId = request.getParameter("roleId");
        int iuserId =0;
        String username ="";
        ResponseInfo responseInfo = new ResponseInfo();
        if(suserId !=null ||( "".equals(suserId)))
        {
            iuserId =  Integer.parseInt(suserId);
            int iroleId =  Integer.parseInt(sroleId);
            userService.authUserByRole(iuserId, iroleId);//保存用户和角色
        }
        responseInfo.setResult("0");
        responseInfo.setMessage(requestContext.getMessage("user.auth.success"));
        WebUtil.responseToJson(response, responseInfo);
    }
    @RequestMapping("/authUserByRole")
    public void authUserByRole(HttpServletRequest request,HttpServletResponse response) {
        String str = request.getParameter("userId");
        int userId =0;
        String username ="";
        ResponseInfo responseInfo = new ResponseInfo();
        if(str !=null ||( "".equals(str)))
        {
            userId =  Integer.parseInt(request.getParameter("userId"));
            User user = userService.getUserById(userId);
            username = user.getUsername();

        }

        List<CrmRole> crmRoleList = crmRoleService.findAllCrmRole(); //获取所有角色
        Map map = crmRoleService.findAllRoleByUserId(userId); //获取用户对应的角色
        responseInfo.setUserId(String.valueOf(userId));
        responseInfo.setUserName(username);
        if(map != null &&( map.size() !=0))
        {
            responseInfo.setRoleId(map.get("roleId").toString());
        }
        responseInfo.setList(crmRoleList);
        responseInfo.setResult("0");
        WebUtil.responseToJson(response,responseInfo);
    }
    @RequestMapping("/getUserAll")
    public void getUserAll(HttpServletResponse response) {
        List<User> userList = userService.findAllUser();
        WebUtil.responseToJson(response,userList);
    }

    @RequestMapping("/getUserBypage")
    public void getUserBypage(HttpServletRequest request,HttpServletResponse response) {
        int pageNumber =Integer.parseInt(request.getParameter("pageNumber"));
        int pageSize =Integer.parseInt(request.getParameter("pageSize"));
        String username = request.getParameter("username");
        List<User> userList =null;
        Long total = null;
        if ((username ==null)||("".equals(username)))
        {
            userList = userService.findAllUserByPageNoParam(pageNumber,pageSize);
            total = userService.findCount();
        }
        else
        {
            userList = userService.findAllUserByPage(pageNumber,pageSize,username);
            total = userService.findCountUsersWithParams(username);
        }
        ResponseInfo responseInfo = new ResponseInfo();
        responseInfo.setList(userList);
        responseInfo.setTotalNumber(total);
        WebUtil.responseToJson(response,responseInfo);
    }
    @RequestMapping("/testjson")
    public String testJson() {

        return "testjson";
    }

    @RequestMapping(value = "/login")
    public String login(@ModelAttribute("User") User userSessionInfor,HttpServletRequest request, HttpServletResponse response)
    {

        RequestContext requestContext = new RequestContext(request);

        ResponseInfo responseInfo = new ResponseInfo();
        HttpSession session = request.getSession();
        User userInfor = null;
        if(!"".equals(userSessionInfor.getPassword()))
        {
//            String md5 = MD5Util.MD5(userSessionInfor.getPasswd());
            logger.info("username:"+userSessionInfor.getUsername());
            logger.info("getPasswd:"+userSessionInfor.getPassword());
            userInfor = userService.getUserByNameAndPasswd(userSessionInfor.getUsername(),userSessionInfor.getPassword());
        }
        if (userInfor != null)
        {
            logger.info("username:" + userInfor.getUsername());
            responseInfo.setResult("0");
            responseInfo.setMessage(userSessionInfor.getUsername());
            responseInfo.setObject(userInfor);
            session.setAttribute("responseInfo", responseInfo);
            return "manage";
        } else {
            responseInfo.setResult("1");
            responseInfo.setMessage(requestContext.getMessage("username.or.password.mistake"));
            session.setAttribute("responseInfo", responseInfo);
            return "loginReturn";
        }
    }


    @RequestMapping("/getJsonValue")
    public void getJsonValue(HttpServletRequest request, HttpServletResponse response) throws IOException {
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        responseInfo.setResult("00000");
        responseInfo.setMessage(requestContext.getMessage("user.username.again"));
//        PrintWriter out = response.getWriter();
//        out.print(responseInfo.toString());
         WebUtil.responseToJson(response,responseInfo);
    }

}